<template>
  <el-dialog width="80%" ref="dialogRef" :model-value="showDialog" @close="closeDialog" align-center>
    <el-tabs v-model="activeName" type="border-card" @tab-click="selectTab">
      <el-tab-pane label="图书库" name="42">
        <ContentWrap>
          <el-table v-loading="loading" :data="list.list" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column
              v-for="(column, index) in list.columns"
              :key="index"
              :prop="column.prop"
              :label="column.label"
              align="center"
            >
              <template #default="scope">
                <el-image
                  v-if="imaged(scope.row[column.prop])"
                  :src="buildImage(column.prop, scope.row)"
                  style="max-width: 100px"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon>
                        <icon-picture />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="资源状态">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.RESOURCE_STATUS" :value="scope.row.status" />
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="total"
            @pagination="handelQuery('42')"
          />
        </ContentWrap>
      </el-tab-pane>
      <el-tab-pane label="图片库" name="picture">
        <ContentWrap>
          <el-table
            v-loading="loading"
            :data="pictureList.list"
            :show-overflow-tooltip="true"
            :stripe="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="center" prop="url" label="图片">
              <template #default="{ row }">
                <el-image :src="row.url" style="max-width: 100px" @click="imagePreview(row.url)" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="名称" />
            <el-table-column align="center" prop="size" label="尺寸" />
            <el-table-column align="center" prop="format" label="格式" />
            <el-table-column align="center" prop="fileSize" label="大小" />
            <el-table-column align="center" prop="createTime" label="创建时间" />
          </el-table>
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="pictureList.total"
            @pagination="handelQuery('picture')"
          />
        </ContentWrap>
      </el-tab-pane>
      <el-tab-pane label="视频库" name="video">
        <ContentWrap>
          <el-table
            v-loading="loading"
            :data="videoList.list"
            :show-overflow-tooltip="true"
            :stripe="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="left" prop="name" label="名称" width="300" />
            <el-table-column align="center" prop="ext" label="格式" />
            <el-table-column align="left" prop="fileSize" label="大小" width="100" />
            <el-table-column align="center" prop="createTime" label="创建时间" />
          </el-table>
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="videoList.total"
            @pagination="handelQuery('video')"
          />
        </ContentWrap>
      </el-tab-pane>
      <el-tab-pane label="音频库" name="audio">
        <ContentWrap>
          <el-table
            v-loading="loading"
            :data="audioList.list"
            :show-overflow-tooltip="true"
            :stripe="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="left" prop="url" label="音频" width="320">
              <template #default="{ row }">
                <audio :src="row.url" controls></audio>
              </template>
            </el-table-column>
            <el-table-column align="left" prop="name" label="名称" />
            <el-table-column align="center" prop="ext" label="格式" />
            <el-table-column align="left" prop="fileSize" label="大小" width="100" />
            <el-table-column align="center" prop="createTime" label="创建时间" />
          </el-table>
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="videoList.total"
            @pagination="handelQuery('audio')"
          />
        </ContentWrap>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button type="primary" @click="closeDialog">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import * as metaApi from '@/api/meta'
import { DICT_TYPE } from '@/utils/dict'
import * as pictureApi from '@/api/picture'
import * as videoApi from '@/api/video'
import * as audioApi from '@/api/audio'
import { createImageViewer } from '@/components/ImageViewer'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { isArray } from '@/utils/is'

const showDialog = ref(false)
const dialogRef = ref()
const activeName = ref('42')
const emit = defineEmits(['paneIsDisabled', 'ResourcesListChange'])
const openDialog = () => {
  showDialog.value = true
}

const closeDialog = () => {
  showDialog.value = false
}
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keyword: null,
  createTime: []
})
const loading = ref(false)
const list = ref([])
const total = ref(0)
const selectTab = async (pane, ev) => {
  let name = pane.props.name
  paneResourceName.value = name
  await handelQuery(name)
}
const pictureList = ref([])
const picturePreviewList = ref([])
const videoList = ref([])
const audioList = ref([])

const paneResourceName = ref('')
/** 提交表单 */
const submitForm = async () => {
  if (selectedItems.value.length != 0) {
    paneResourceName.value = paneResourceName.value == '' ? '42' : paneResourceName.value
    emit('ResourcesListChange', selectedItems.value, paneResourceName.value)
  }
  closeDialog()
}
const selectedItems = ref([])
const handleSelectionChange = (row) => {
  selectedItems.value = row
}

const handelQuery = async (name) => {
  loading.value = true
  if (name == 'picture') {
    queryParams.type = 10
    pictureList.value = await pictureApi.page(queryParams)
    picturePreviewList.value = []
    pictureList.value.list.forEach((key, index) => {
      picturePreviewList.value.push(key.url)
    })
  } else if (name == 'video') {
    videoList.value = await videoApi.page(queryParams)
  } else if (name == 'audio') {
    audioList.value = await audioApi.page(queryParams)
  } else {
    list.value = await metaApi.selectData(name, queryParams)
    total.value = list.value.total
  }
  loading.value = false
}
/** 商品图预览 */
const imagePreview = (args) => {
  const urlList = []
  if (isArray(args)) {
    args.forEach((item) => {
      urlList.push(item.url)
    })
  } else {
    urlList.push(args)
  }
  createImageViewer({
    urlList
  })
}

function isNumber(str: string): boolean {
  return /^\d+$/.test(str) // 只包含数字的正则表达式
}

const imaged = (row) => {
  if (!row) {
    return false
  }
  if (isNumber(row)) {
    return false
  }
  return isValidJson(row)
}
const buildImage = (name, row) => {
  if (JSON.parse(row[name]).length > 0) {
    return JSON.parse(row[name].replaceAll('\\', ''))[0].url
    // return JSON.parse(row[name])[0].url
  } else {
    return ''
  }
}

function isValidJson(str) {
  if (str.startsWith('{') || str.startsWith('[')) {
    if (str.endsWith(']') || str.endsWith('}')) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}

defineExpose({ openDialog })

onMounted(() => {
  handelQuery(activeName.value)
})
</script>
<style scoped></style>
